import { HTTP, VERSION } from "../config";
const app = getApp();

export default function (option) {
    // const app = getApp()

    return new Promise((resolve, reject) => {
        console.log("请求数据", option.data);
        console.log("请求地址", option.url);
        wx.request({
            url: option.url.indexOf("http") > -1 ? option.url : HTTP + option.url,
            data: option.data,
            header: {
                "content-type": "application/json",
                openId: wx.getStorageSync("XOP-Security-Id"),
                version: VERSION
            },
            method: option.method,
            dataType: "json",
            responseType: "text",
            success: (result) => {
                const ret = result;
                console.log("响应数据", result, ret.data);
                if ([401].includes(ret.data.code)) {
                    const pages = getCurrentPages();
                    if (pages && pages[pages.length - 1].route !== "pages/index/index" && !app.currentPageIndex) {
                        app.currentPageIndex = true;
                        wx.removeStorageSync("XOP-Security-Id");
                        wx.reLaunch({
                            url: "/pages/index/index"
                        });
                    }
                    resolve(ret.data);
                    return;
                }

                if (ret.statusCode !== 200) {
                    wx.showToast({ title: ret.data.error, icon: "none" });
                    resolve(ret.data);
                    return;
                }

                if (ret.data.code !== 200) {
                    wx.showToast({ title: ret.data.msg, icon: "none" });
                    resolve(ret.data);
                    return;
                }
                resolve(ret.data);
            },
            fail: (err) => {
                wx.showToast({ title: "请求异常,请检查网络", icon: "none" });
                reject(err);
            },
            complete: () => {}
        });
    }).catch(() => {});
}
